//
//  JZBAddPayViewController.m
//  JZB
//
//  Created by liujianlong on 2022/8/31.
//

#import "JZBAddPayViewController.h"
#import "JZBAddCell.h"
#import "JZBAddHeader.h"
#import "JZBAddFooter.h"
#import "JZBAddFoodFooter.h"
@interface JZBAddPayViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) NSArray *array;
@property (nonatomic, strong) NSArray *content;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) JZBAddHeader *header;
@property (nonatomic, strong) JZBAddFooter *footer;
@end

@implementation JZBAddPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setupNaviBarColor:[UIColor colorWithHexString:@"#F9DB61"] titleColor:[UIColor blackColor]];
}
- (void)initUI
{
    [self setupNaviBarColor:[UIColor whiteColor] titleColor:[UIColor blackColor]];
    self.view.backgroundColor = [UIColor whiteColor];
    
    WS(self)
    self.header = [JZBAddHeader loadFromXIB];
    self.footer = [JZBAddFooter loadFromXIB];
    self.footer.addImgBlock = ^{
        [weakself addPhoto];
    };
    self.tableviewstyle = UITableViewStyleGrouped;
    [self.tableView registerNib:[JZBAddCell nib] forCellReuseIdentifier:[JZBAddCell ID]];
    for (NSLayoutConstraint *c in self.view.constraints) {
        if ([c.firstItem isEqual:self.tableView] && c.firstAttribute == NSLayoutAttributeBottom) {
            c.constant = -76;
        }
    }
    
    [self update];
    
    self.loginBtn = [UIButton new];
    self.loginBtn.bounds = CGRectMake(0, 0, SCREEN_WIDTH - 40, 56);
    self.loginBtn.translatesAutoresizingMaskIntoConstraints = NO;
    self.loginBtn.cornerRadius = 28;
    self.loginBtn.textHexColor = @"#323036";
    self.loginBtn.backGroudHexColor = @"#F9DB61";
    [self.loginBtn setTitle:LS(@"完成") forState:UIControlStateNormal];
    [self.loginBtn addTarget:self action:@selector(actionForEnterBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    NSLayoutConstraint *height = [self.loginBtn a1:NSLayoutAttributeHeight e:NSLayoutRelationEqual t:nil a2:NSLayoutAttributeNotAnAttribute c:56];
    NSLayoutConstraint *width = [self.loginBtn a1:NSLayoutAttributeWidth e:NSLayoutRelationEqual t:nil a2:NSLayoutAttributeNotAnAttribute c:SCREEN_WIDTH - 40];
    NSLayoutConstraint *centerx = [self.loginBtn a1:NSLayoutAttributeCenterX e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeCenterX c:0];
    NSLayoutConstraint *bottom = [self.loginBtn a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeBottom c: -20];
    [self.view addConstraints:@[height,width,bottom,centerx]];
}
- (void)update{
    self.header.img.image = [UIImage imageNamed:self.model.type];
    self.header.name.text = LS(self.model.type);
    self.title = self.style == AddStylePay ? LS(@"添加支出") : LS(@"添加收入");
    self.array = self.style == AddStylePay ? @[@[@"支付金额"],@[@"支付方式",@"支付地址"]] : @[@[@"收入金额",@"收入方式"]];
    self.content = self.style == AddStylePay ? @[@[self.model.money],@[self.model.from, self.model.address]] : @[@[self.model.money,self.model.from]];
    self.footer.imgDatas = self.model.data;
    [self.tableView reloadData];
}
#pragma mark - 保存
- (void)actionForEnterBtn{
    if (self.model.money.length <= 0) {
        return [RLHud msg:LS(@"金额不能为空")];
    }else if (self.model.from.length <= 0){
        return [RLHud msg:LS(@"方式不能为空")];
    }else if (self.style == AddStylePay && self.model.address.length <= 0){
        return [RLHud msg:LS(@"地址不能为空")];
    }
    [RLHud startHud:LS(@"保存中...")];
    [self.model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:notifyBookUpdate object:nil];
            [RLHud startHud:LS(@"保存成功") stopTime:1 handle:^{
                [self backBtnAction];
            }];
        });
    }];
}
#pragma mark - 添加照片
- (void)addPhoto{
    WS(self)
    [weakself sheet:nil msg:nil sheet:@[@"相机",@"相簿"] sheetBlock:^(int index, NSString *sheetTitle) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [RLHud startHud];
        });
        UIImagePickerController *vc = [[UIImagePickerController alloc] init];
        vc.delegate = self;
        vc.allowsEditing = YES;
        vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [weakself presentViewController:vc animated:YES completion:^{
            [RLHud stopHud];
        }];
    }];
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    UIImage *img = [info valueForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(img, 0.5);
    [self.model.data addObject:imageData];
    [self update];
    [picker dismissViewControllerAnimated:NO completion:nil];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.array.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  [self.array[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JZBAddCell *cell = [tableView dequeueReusableCellWithIdentifier:[JZBAddCell ID]];
    NSString *str = self.array[indexPath.section][indexPath.row];
    cell.name.text = LS(str);
    cell.input.text = LS(self.content[indexPath.section][indexPath.row]);
    cell.input.enabled = ![str containsString:@"方式"];
    cell.inputNumber = [str containsString:@"金额"];
    WS(self)
    cell.inputBlock = ^(NSString * _Nonnull text) {
        if ([str containsString:@"金额"]) {
            weakself.model.money = text;
        }else if (weakself.style == AddStylePay && [str isEqualToString:@"支付地址"]){
            weakself.model.address = text;
        }
    };
    return  cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == self.array.count - 1){
        return self.footer.H;
    }else if (section == 0 && self.style == AddStylePay && [self.model.type isEqualToString:@"餐饮"]){
        return 44;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0 ? self.header.frame.size.height : 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == self.array.count - 1){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.footer.H)];
        self.footer.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.footer.H);
        
        [view addSubview:self.footer];
        return view;
    }else if (section == 0 && self.style == AddStylePay && [self.model.type isEqualToString:@"餐饮"]){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        JZBAddFoodFooter *food = [JZBAddFoodFooter loadFromXIB];
        food.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
        food.block = ^(int tag) {
            
        };
        [view addSubview:food];
        return view;
    }
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 110)];
        [view addSubview:self.header];
        return view;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = self.array[indexPath.section][indexPath.row];
    if ([str containsString:@"方式"]) {
        WS(self)
        [self sheet:LS(str) msg:nil sheet:@[@"支付宝",@"微信",@"applePay",@"银行卡",@"其他"] sheetBlock:^(int index, NSString *sheetTitle) {
            weakself.model.from = sheetTitle;
            [weakself update];
        }];
    }
}
@end
